package itsm.isperp.module.controller.api.monitor;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.DateUtils;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.dto.configuration.ConfCiDTO;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.slm.SlmServiceTargetService;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 来自监控平台的告警接口
 * 
 * 
 * @author lizx
 * @date 2014-5-19
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/monitor/alarm")
public class AlarmController {

  @Autowired
  IcdIncidentService icdIncidentService;

  @Autowired
  ConfCiService confCiService;

  @Autowired
  AppUserService appUserService;

  @Autowired
  AppDictService appDictService;
  
  @Autowired
  JdbcTemplate jdbcTemplate;
  public static final Logger logger = LoggerFactory
      .getLogger(AlarmController.class);

  /**
   * 告警申报接口
   * 
   * @param request
   * @return
   * @throws Exception
   */
  @RequestMapping("save")
  @ResponseBody
  public String save(HttpServletRequest request) throws Exception {

    // AlarmType（包括告警与恢复告警两种）
    String moId = request.getParameter("moId");// 获取ip
    String priority = request.getParameter("priority");// 级别
    String postType = request.getParameter("postType");
    String title = request.getParameter("title");
    String project=request.getParameter("projectname");
    String category=request.getParameter("category");
    
    String description = request.getParameter("description");
    logger.info("moId:" + moId + ",priority:" + priority + ",postType"
        + postType + ",title:" + title + ",desciption:" + description);
    IcdIncident entity = new IcdIncident();
    String eventId = request.getParameter("eventId");
    if(StringUtils.isEmpty(eventId))
      eventId=HibernateUUIDGenerator.generate();
    String alarmType = request.getParameter("alarmType");
    String ip = "";
    String customerId="";
    
    if(StringUtils.isEmpty(alarmType))
    {
      alarmType="1";
    }

    // 得到关联的资产
    if (StringUtils.isNotEmpty(moId)) {

      moId = moId.replace("'", "").trim();
      String ciId = "";
      ConfCi ci = confCiService.findOneByCode(moId);
      if (ci != null) {
        ciId = ci.getId();
      } else {
        List<ConfCiDTO> confCi = confCiService.findByProperty("IP", ip, "id");
        ciId = (confCi == null || confCi.size() == 0) ? null : confCi.get(0)
            .getId();
      }
      if (StringUtils.isNotBlank(ciId))
        entity.setCiId(ciId);
    }
    //匹配项目
    if(StringUtils.isNoneBlank(project))
    {
      ProjProjectService projProjectService=ContextHolder.getSpringBean("projProjectService");
      JqGridRequest req=new JqGridRequest();
      req.addFilterRule("name", JqGridFilterRuleOp.eq, project);
      ProjProject prj=projProjectService.findOneByRequest(req);
      if(prj!=null)
      {
        entity.setProjectId(prj.getId());
        customerId=prj.getCusCustomerId();
      }
      description=description+"\n"+"项目："+project;
      
    }
    if(StringUtils.isNotBlank(moId))
      description=description+"\n"+"IP地址："+moId;
    //匹配类别
    if(StringUtils.isNotBlank(category))
    {
      AppDict apd=appDictService.findByTypeAndCodeValue("ALARM_ITSS_CATEGORY", category);
      if(apd!=null)
      {
        String categoryName=apd.getName();
        String sql="select id from icd_category where name='"+categoryName+"'";
        List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
        if(list.size()>0)
        {
          entity.setIcdCategoryId(list.get(0).get("id").toString());
          entity.setIcdCategoryName(categoryName);
        }
      }
      description=description+"\n"+"监控类别："+category;
    }
    String cus_user_id="";
    String creator="alarm";
    String creatorName="监控系统";
    String source="";
    String getUserSql="select * from app_user where  fullname like '%监控系统%' limit 1";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(getUserSql);
    if(list.size()>0)
    {
      cus_user_id=list.get(0).get("id").toString();
      creator=list.get(0).get("name").toString();
      creatorName=list.get(0).get("fullname").toString();
    }
    //AppUser ausUser = appUserService.findByUsername("alarm");
    // 请求人--监控中心
    entity.setCusUserId(cus_user_id);
    entity.setId(eventId);
    Timestamp d = new Timestamp(System.currentTimeMillis());
    entity.setCreateDate(d);
    entity.setCreator(creator);
    entity.setCreatorName(creatorName);
    entity.setSource("监控系统");
    entity.setTitle(title);
    String priorityName = "三级";
    if (StringUtils.isNotEmpty(priority)) {
      switch (priority) {
      case "2":
        priorityName = "二级";
        break;
      case "1":
        priorityName = "一级";
        break;
      case "3":
        priorityName = "三级";
        break;
      case "4":
        priorityName = "四级";
        break;
      default:
        break;
      }
    } 
 
    // 级别匹配
    /*
     * List<AppDict> dicts = appDictService.findByType("INCIDENT_priority");
     * String priorityName = null; FIND_PRIORITY: for (AppDict d : dicts) { if
     * (d.getOrderNum().toString().equals(priority)) { priorityName =
     * d.getName(); break FIND_PRIORITY; } }
     */

    entity.setPriorityName(priorityName);
    entity.setDescription(description);
    entity.setStatus(appDictService.getInitStatus("INCIDENT_STATUS"));
    // entity.setServiceCategoryId("0000029f6c6d074c000d");
    // entity.setIcdCategoryId("0000029f6c6be79d000f");
    // entity.setIcdCategoryName("故障处理");
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean(BpmProcessRunService.class);
    try
    {
      if (alarmType.equals("1")) {
        icdIncidentService.saveOrUpdate(entity);
        if (StringUtils.isEmpty(postType) || "1".equals(postType)) {

          String id=entity.getId();
          String sql1="select * from icd_incident_moniotr_staup where icd_id='"+id+"'";
          List<Map<String,Object>> list1=jdbcTemplate.queryForList(sql1);
          if(list1.size()==0)
          {
            bpmProcessRunService.startProcess("alarm", "incidentProcess",
                entity.getId(), null);
            String sql2="insert into icd_incident_moniotr_staup(id,icd_id,create_date) values(uuid(),'"+id+"',now())";
            jdbcTemplate.update(sql2);
          }
         
        }
      } else if (alarmType.equals("0")) {
        if (icdIncidentService.exists(entity.getId()))
          bpmProcessRunService.endProcessByBusinessId("alarm", entity.getId(),
              "恢复告警");
      }
    }catch(Exception ex)
    {
      return "{msg:'fail',eventId:'"+eventId+"'}";
    }
    

    return "{msg:'success',eventId:'"+eventId+"'}";
  }
  
  @RequestMapping("incidentInfo")
  public ModelAndView incidentInfo(String id) {
    ModelAndView mv = new ModelAndView("api/monitor/incidentInfo");
    setIncidentInfoModelAndView(mv, id);
    return mv;
  }
  
  private void setIncidentInfoModelAndView(ModelAndView mv, String id) {

    IcdIncident entity = icdIncidentService.findOne(id);

    String descStep1 = "登记于" + DateUtils.formatDateTime(entity.getCreateDate())
        + "。";

    String unfinishClass = "list-unfinish";

    String step2 = null, step3 = null, step4 = null, step5 = null, step6 = null, descStep2 = null, descStep3 = null, descStep4 = null, descStep5 = null, descStep6 = null;

    step2 = step3 = step4 = step5 = step6 = unfinishClass;
    AppUserService appUserService = ContextHolder
        .getSpringBean(AppUserService.class);
    if (entity.getAssignDate() != null
        && StringUtils.isNotEmpty(entity.getSupporterId())) {
      step2 = "";
      AppUser supporter = appUserService
          .findByUsername(entity.getSupporterId());
      String slmDesc = "";

      if (StringUtils.isNotEmpty(entity.getSlmId())) {

        SlmServiceTargetService slmServiceTargetService = ContextHolder
            .getSpringBean(SlmServiceTargetService.class);

        List<Map<String, Object>> slmList = slmServiceTargetService
            .findSlmServiceTargetsValue(entity.getSlmId(), entity.getId());

        for (Map<String, Object> m : slmList) {
          slmDesc += "[" + m.get("target_name") + ":" + m.get("plan_value")
              + "]  ";
        }
      }

      descStep2 = "您的事件单于" + DateUtils.formatDateTime(entity.getAssignDate())
          + "分派至工程师    " + supporter.getFullname() + "(电话："
          + supporter.getMobile() + ")。" + slmDesc;

      step3 = step4 = step5 = step6 = unfinishClass;
    }

    if (entity.getResponseDate() != null) {
      step2 = "";
      step3 = "";
      AppUser responser = appUserService
          .findByUsername(entity.getResponserId());
      descStep3 = "工程师    "
          + (responser == null ? "" : responser.getFullname() + "(电话："
              + responser.getMobile() + ")") + " 于"
          + DateUtils.formatDateTime(entity.getResponseDate()) + "响应了您的问题。";

    }

    if (entity.getArrivalDate() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      AppUser arriver = appUserService.findByUsername(entity.getArriverId());
      descStep4 = "工程师    "
          + (arriver == null ? "" : arriver.getFullname() + "(电话："
              + arriver.getMobile() + ")") + " 于"
          + DateUtils.formatDateTime(entity.getArrivalDate()) + "到达事件现场。";

    }

    if (entity.getSolverSubmitTime() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      step5 = "";
      AppUser solver = appUserService.findByUsername(entity.getSolverId());

      descStep5 = "工程师    "
          + (solver == null ? "" : solver.getFullname() + "(电话："
              + solver.getMobile() + ")") + " 于"
          + DateUtils.formatDateTime(entity.getSolverSubmitTime()) + "解决了此问题。";

    }

    if (entity.getClosedDate() != null) {
      step2 = "";
      step3 = "";
      step4 = "";
      step5 = "";
      step6 = "";

      descStep6 = "事件单关闭于" + DateUtils.formatDateTime(entity.getClosedDate())
          + "。";
    }

    mv.addObject("step2", step2);
    mv.addObject("step3", step3);
    mv.addObject("step4", step4);
    mv.addObject("step5", step5);
    mv.addObject("step6", step6);

    mv.addObject("descStep1", descStep1);
    mv.addObject("descStep2", descStep2);
    mv.addObject("descStep3", descStep3);
    mv.addObject("descStep4", descStep4);
    mv.addObject("descStep5", descStep5);
    mv.addObject("descStep6", descStep6);

    mv.addObject("model", entity);
  }
  
}
